#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2011-11-12
@author: shell.xu
'''
import os, sys, logging, thread
import pymongo
import config, mqsrv, service
import atcidx
from os import path
config.basedir = path.dirname(path.dirname(path.realpath(__file__)))

# 服务的配置
logging.basicConfig(level = logging.DEBUG)
config.mongo = pymongo.Connection('localhost', 27017)
config.db = config.mongo['pyblog']
config.idxpath = path.join(config.basedir, 'indexes')
config.segdbname = 'frq.db'
atcfunces = atcidx.xapian_env('articles', atcidx.atcdoc)

def zmqloop():
    handlers = {}
    handlers['search_article'] = atcfunces[2]
    mqsrv.zmqloop(handlers, 'tcp://127.0.0.1:5556')

def btmqloop():
    handlers = {}
    handlers['update_article'] = atcfunces[0]
    handlers['remove_article'] = atcfunces[1]
    mqsrv.btmqloop(handlers)

def upatcnew():
    for atc in config.db['articles'].find({'did':{'$exists':False}}):
        atcfunces[0](atc['_id'])

def upatcall():
    for atc in config.db['articles'].find(): atcfunces[0](atc['_id'])

def searchatc(query):
    for did, rank, aid in atcfunces[2](query, 0, 20)[1]:
        print 'hit docid: %s, rank: %s, aid: %s' % (did, rank, aid)

# 多种启动参数，直接启动为服务
def main():
    lockpath = path.join(config.idxpath, 'wdb.lock')
    if len(sys.argv) == 1:
        with service.lockfile(lockpath):
            thread.start_new_thread(zmqloop, ())
            btmqloop()
    elif sys.argv[1] == 'upatc':
        # upatc article id .. 更新对应文章的索引记录
        with service.lockfile(lockpath):
            for i in sys.argv[2]: atcfunces[0](i)
    elif sys.argv[1] == 'upatcnew':
        # upatcnew 更新所有文章的索引记录
        with service.lockfile(lockpath):
            upatcnew()
    elif sys.argv[1] == 'upatcall':
        # upatcnew 更新所有文章的索引记录
        with service.lockfile(lockpath):
            upatcall()
    elif sys.argv[1] == 'searchatc': searchatc(sys.argv[2])
    # searchatc query .. 检索特定内容

if __name__ == '__main__': main()
